<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\Facades\DB;

class Class_section_group extends Model
{
	public $timestamps = false;
    protected $fillable = [
        'pid','name','type', 'description',
    ];

    public function ClassSection()
    {
        return $this->belongsTo(Squad::class);
    }
    public function ClassGroup()
    {
        return $this->belongsTo(Squad::class);
    }
    public function parent()
    {
        return $this->belongsTo(Class_section_group::class, 'pid');
    }
    public function children()
    {
        return $this->hasMany(Class_section_group::class, 'pid');
    }

    public function brothers()
    {
        return $this->parent->children();
    }

    public static function options($id)
    {
        if (! $self = static::find($id)) {
            return [];
        }

        return $self->brothers()->pluck('name', 'id');
    }

    public function getChargeAttribute($value)
    {
        return explode(',', $value);
    }

    public function setChargeAttribute($value)
    {
        $this->attributes['charge'] = implode(',', $value);
    }

    public static function regulate_options($action=1){
        $user = Admin::user()->id;

        $data = DB::select('SELECT id,name FROM class_section_groups WHERE (pid=0 AND FIND_IN_SET(?,`charge`) 
OR (id IN (SELECT pid FROM class_section_groups WHERE pid>0 AND FIND_IN_SET(?,`charge`))))',[$user,$user]);

        $data1 = DB::table('squads as s')->join('class_section_groups as c','s.section','=','c.id')
            ->where('s.class_teacher','=',$user)->select('c.id','c.name')->get();

        $option = array();
        if($action == 1){
            $option[0] = '全部';
        }
        foreach($data as $v){
            $option[$v->id]=$v->name;
        }
        foreach($data1 as $v){
            $option[$v->id]=$v->name;
        }

        return $option;
    }
}
